<?php
/**
 * Created by jinqiang on 2024/7/11 11:09.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Wms;


use App\Http\Models\Mysql\SsyPurchaseReturnTable;
use App\Http\Models\Mysql\SsyTaobaoQimenStockoutConfirmTable;

class ItemReturnService
{
    public function search($param)
    {
        $conn = (new SsyPurchaseReturnTable())->where('groups', $param['groups']);
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('processing_code', $param['processing_code']);
        }
        if($param['jy_number'] ?? ""){
            $conn = $conn->where('jy_number', $param['jy_number']);
        }
        if($param['sku_code'] ?? ""){
            $conn = $conn->where('sku_code', 'like', $param['sku_code'].'%');
        }
        if($param['factory_name'] ?? ""){
            $conn = $conn->where('factory_name', 'like', '%'.$param['factory_name'].'%');
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $jyNumber = array_column($res['data'], 'jy_number');
        $skuCodes = array_column($res['data'], 'sku_code');
        //获取采退返修的实际数据
        $stockoutList = (new SsyTaobaoQimenStockoutConfirmTable())->whereIn('deliveryOrderId', $jyNumber)->whereIn('itemCode', $skuCodes)
            ->get(['deliveryOrderId', 'itemCode', 'actualqty'])->toArray();
        $actualqtyList = [];
        foreach ($stockoutList as $item){
            $actualqtyList[$item['deliveryOrderId'].$item['itemCode']] = $item['actualqty'];
        }
        foreach ($res['data'] as &$item){
            if(isset($actualqtyList[$item['jy_number'].$item['sku_code']])){
                $item['sj_num'] = $actualqtyList[$item['jy_number'].$item['sku_code']];
            }
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }
}
